package com.bw.login.vm

import androidx.lifecycle.MutableLiveData
import com.bw.common.entity.UserEntity
import com.bw.common.vm.BaseViewModel
import com.bw.login.model.LoginRepository
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(private val repo :LoginRepository):BaseViewModel() {
    val mLoginSuccess=MutableLiveData<UserEntity>()
    /**
     * 账号和密码登录
     */
    fun loginToServer(userName:String,password:String){
        mViewModelScope.launch(mDispatcher) {
            //采用解构方式获取返回字段
            val  res = repo.loginToServer(userName,password)
            if (res.code ==200){
                mLoginSuccess.postValue(res.data.apply {
                    typeId = 1 // 代表为登录返回
                })
                //保存Token
                MMKV.defaultMMKV().run {
                    encode("token",res.data.token)
                    encode("userId",res.data.id)
                }
            }else{
                mError.postValue(res.message)
            }
        }
    }

    /**
     * 新账号注册
     */
    fun registerToServer(userName:String,password: String){
        mViewModelScope.launch(mDispatcher) {
            //采用解构方式获取返回字段
            val res = repo.registerToServer(userName,password)
            if (res.code == 200){
                mLoginSuccess.postValue(res.data.apply {
                    typeId = 0
                })
            }else{
                mError.postValue("注册失败！！")
            }
        }
    }
}